import libtcodpy as libtcod

import events

class Fov(events.EventListener):
	def __init__(self):
		super(Fov,self).__init__()
		
		self.fov_map = libtcod.map_new(100,100)
	
	def update_map(self):
		viewport = self.em.services["render"].viewport
		map = self.em.services["map"]

		for i in xrange(viewport.w):
			for j in xrange(viewport.h):
				(x,y) = viewport.cord_world(i,j)
				#(x,y) = (i,j)
				
				tile = map.get_tile(x,y)
				if tile:
					libtcod.map_set_properties(self.fov_map, i, j,
						not tile.block_sight,
						not tile.blocked)

						
	def tile_visible(self, x, y):
		viewport = self.em.services["render"].viewport
		(i,j) = viewport.cord_view(x,y)
		if i > 0 and i < viewport.w:
			if j > 0 and j < viewport.h:
				return libtcod.map_is_in_fov(self.fov_map, i, j)
				
		return False
		
	def recompute(self, player):
		FOV_LIGHT_WALLS = True
		FOV_ALGO = 0
		
		self.update_map()
		
		(i,j) = self.em.services["render"].viewport.cord_view(player.x,player.y)
		libtcod.map_compute_fov(self.fov_map, i, j, player.get_fov_radius(), FOV_LIGHT_WALLS, FOV_ALGO)
